﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace B.S.AuthCenter.Common
{
    public class JwtTools
    {
        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="configuration">配置接口</param>
        /// <param name="uid">用户唯一标识</param>
        /// <returns></returns>
        public string JwtNewString(IConfiguration configuration,string uid)
        {
            //生成JWT
            //Header,选择签名算法
            var signingAlogorithm=SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息，放了一个用户Uid
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Name,"张三"),
                new Claim(ClaimTypes.Email,"2548174437@qq.com"),
                new Claim(ClaimTypes.Role,"管理员"),
                new Claim(ClaimTypes.DateOfBirth,"2004-3-6",ClaimValueTypes.Date),
                new Claim("CustomClaimType","CustomValue"),
                new Claim("key","value")
            };
            //取出私钥并以Utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey=new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials=new SigningCredentials(signingKey,signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],//发布者
                audience: configuration["Authentication:Audience"],//接收者
                claims:claims,                                      //存放的用户信息
                notBefore:DateTime.UtcNow,                          //发布时间
                expires:DateTime.UtcNow.AddDays(1),                 //有效期设置一天
                signingCredentials                                  //数字签名
             );
            //生成字符串token
            var TokenStr=new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }
    }
}
